package com.code.monitor.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author ggh
 * @date 2023/4/27
 */
public class HttpUtils {
    public static String doGet(String uri, int timeout) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();

        try {
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setConfig(defaultRequestConfig);

            CloseableHttpResponse responses = httpClient.execute(httpGet);
            HttpEntity responseEntity = responses.getEntity();
            String result = EntityUtils.toString(responseEntity, Charset.defaultCharset());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String doPost(String uri, HttpEntity httpEntity, int timeout) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();

        try {
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setConfig(defaultRequestConfig);
            httpPost.setEntity(httpEntity);

            CloseableHttpResponse responses = httpClient.execute(httpPost);
            HttpEntity responseEntity = responses.getEntity();
            String result = EntityUtils.toString(responseEntity, Charset.defaultCharset());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(doGet("http://localhost:8899/autoTask/config", 5000));
    }
}
